package org.dromara.apartment.service.impl;

import org.dromara.apartment.domain.enums.AppointmentStatus;
import org.dromara.apartment.service.IApartmentInfoService;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.satoken.utils.LoginHelper;
import org.springframework.stereotype.Service;
import org.dromara.apartment.domain.bo.ViewAppointmentBo;
import org.dromara.apartment.domain.vo.ViewAppointmentVo;
import org.dromara.apartment.domain.ViewAppointment;
import org.dromara.apartment.mapper.ViewAppointmentMapper;
import org.dromara.apartment.service.IViewAppointmentService;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 预约看房信息Service业务层处理
 *
 * @author CKJ
 * @date 2025-06-30
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class ViewAppointmentServiceImpl implements IViewAppointmentService {

    private final ViewAppointmentMapper baseMapper;
    private final IApartmentInfoService apartmentInfoService;

    /**
     * 查询预约看房信息
     *
     * @param id 主键
     * @return 预约看房信息
     */
    @Override
    public ViewAppointmentVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询预约看房信息列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 预约看房信息分页列表
     */
    @Override
    public TableDataInfo<ViewAppointmentVo> queryPageList(ViewAppointmentBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ViewAppointment> lqw = buildQueryWrapper(bo);
        Page<ViewAppointmentVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        result.getRecords().stream().forEach(item->{
            item.setApartmentInfoVo(apartmentInfoService.queryAppInfoById(item.getApartmentId()));
        });
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的预约看房信息列表
     *
     * @param bo 查询条件
     * @return 预约看房信息列表
     */
    @Override
    public List<ViewAppointmentVo> queryList(ViewAppointmentBo bo) {
        LambdaQueryWrapper<ViewAppointment> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ViewAppointment> buildQueryWrapper(ViewAppointmentBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ViewAppointment> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(ViewAppointment::getId);
        lqw.eq(bo.getUserId() != null, ViewAppointment::getUserId, bo.getUserId());
        lqw.like(StringUtils.isNotBlank(bo.getName()), ViewAppointment::getName, bo.getName());
        lqw.eq(StringUtils.isNotBlank(bo.getPhone()), ViewAppointment::getPhone, bo.getPhone());
        lqw.eq(bo.getApartmentId() != null, ViewAppointment::getApartmentId, bo.getApartmentId());
        lqw.eq(bo.getRoomId() != null, ViewAppointment::getRoomId, bo.getRoomId());
        lqw.eq(bo.getAppointmentTime() != null, ViewAppointment::getAppointmentTime, bo.getAppointmentTime());
        lqw.eq(StringUtils.isNotBlank(bo.getAdditionalInfo()), ViewAppointment::getAdditionalInfo, bo.getAdditionalInfo());
        lqw.eq(bo.getAppointmentStatus() != null, ViewAppointment::getAppointmentStatus, bo.getAppointmentStatus());
        return lqw;
    }

    /**
     * 新增预约看房信息
     *
     * @param bo 预约看房信息
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(ViewAppointmentBo bo) {
        ViewAppointment add = MapstructUtils.convert(bo, ViewAppointment.class);
        add.setUserId(LoginHelper.getAppLoginUser().getId());
        add.setAppointmentStatus(AppointmentStatus.TO_BE_VIEWED.getType());
        if(StringUtils.isBlank(add.getName())){
            add.setName(LoginHelper.getAppLoginUser().getNickname());
        }
        if(StringUtils.isBlank(add.getPhone())){
            add.setPhone(LoginHelper.getAppLoginUser().getMobile());
        }
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改预约看房信息
     *
     * @param bo 预约看房信息
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(ViewAppointmentBo bo) {
        ViewAppointment update = MapstructUtils.convert(bo, ViewAppointment.class);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ViewAppointment entity){
        Long appointmentCount = baseMapper.selectCount(new LambdaQueryWrapper<ViewAppointment>().eq(ViewAppointment::getApartmentId,entity.getApartmentId()).eq(ViewAppointment::getUserId,entity.getUserId()).ne(ViewAppointment::getAppointmentStatus, AppointmentStatus.CANCELLED));
        if(appointmentCount > 0){
            throw new ServiceException("当前已预约！请勿重复预约！");
        }
    }

    /**
     * 校验并批量删除预约看房信息信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }
}
